import { useEffect, useState } from 'react'
import './index.scss'
// import { UserCircleOutline } from 'antd-mobile-icons'
import axios from '../../api/index'
import { Tabs } from 'antd-mobile'
import { useSearchParams } from 'react-router-dom'
//
interface DoctorItem {
  doctorId: number
  doctorName: string
  imagePic: string
  jobTitle: string
  inauguralHospital: string
  praise: number
  serverNum: number
  servicePrice: number
  praiseNum: number
  badNum: number
}
import Nabbar from '../../extract/index'
interface DepartmentItem { id: number; departmentName: string }
import { useNavigate } from 'react-router-dom'
//
function Ks() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const [data, setData] = useState<DoctorItem[]>([])
  const [title, setTitle] = useState<DepartmentItem[]>([])
  const [sortKey, setSortKey] = useState('综合') // 综合 | 好评 | 咨询量 | 价格
  const [priceAsc, setPriceAsc] = useState(true)
  const [deptId, setDeptId] = useState(1)
  const [page] = useState(1)
  const [count] = useState(20)
  const [activeIdx, setActiveIdx] = useState(0)
  const [pageIdx, setPageIdx] = useState(0) // 分页索引
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [departmentsLoaded, setDepartmentsLoaded] = useState(false)
  // 获取科室列表
  useEffect(() => {
    setLoading(true)
    setError(null)
    axios.get('/share/knowledgeBase/v1/findDepartment', {
    }).then(res => {
      const list: DepartmentItem[] = res?.data?.result || []
      setTitle(list)
      setDepartmentsLoaded(true)
      
      // 从URL参数获取科室ID
      const urlDeptId = searchParams.get('deptId')
      if (urlDeptId) {
        const targetDept = list.find(item => item.id === Number(urlDeptId))
        if (targetDept) {
          setDeptId(targetDept.id)
          return
        }
      }
      
      // 如果没有URL参数或找不到对应科室，默认内科
      const neike = list.find(item => item.departmentName === '内科')
      if (neike?.id) {
        setDeptId(neike.id)
      } else if (list.length > 0) {
        setDeptId(list[0].id)
      }
    }).catch(err => {
      console.error('[KS] 获取科室列表失败:', err)
      setError('获取科室列表失败，请重试')
    }).finally(() => {
      setLoading(false)
    })
  }, [searchParams])
  // 获取医生列表
  useEffect(() => {
    // 只有当科室列表加载完成且有有效的deptId时才请求医生列表
    if (!departmentsLoaded || !deptId) {
      return
    }
    
    setLoading(true)
    setError(null)
    
    const conditionMap = { '综合': 1, '好评': 2, '咨询量': 3, '价格': 4 } as const
    const condition = conditionMap[sortKey as keyof typeof conditionMap]
    const sortBy = sortKey === '价格' ? (priceAsc ? 1 : 2) : undefined
    const params: Record<string, number> = { deptId, page, count }
    params.condition = condition
    if (sortBy !== undefined) params.sortBy = sortBy
    console.log('[KS] findDoctorList params', params)
    
    axios.get('/user/inquiry/v1/findDoctorList', { params })
      .then(res => {
        console.log('[KS] success', res?.status)
        const doctorList = res?.data?.result || []
        setData(doctorList)
        if (doctorList.length === 0) {
          setError('暂无医生数据')
        }
      })
      .catch(err => {
        console.error('[KS] error', err?.response?.status, err?.response?.data)
        setError('获取医生列表失败，请重试')
        setData([])
      })
      .finally(() => {
        setLoading(false)
      })
  }, [deptId, page, count, sortKey, priceAsc, departmentsLoaded])
  // 分页

  useEffect(() => {
    setPageIdx(0)
    setActiveIdx(0)
  }, [data])

  const pageSize = 3
  const pageCount = Math.max(1, Math.ceil(data.length / pageSize))
  const start = pageIdx * pageSize
  const end = start + pageSize
  const visible = data.slice(start, end)
  const current = data[start + activeIdx]

  return (
    <div className='byq'>
      <div className='b_top'>
        <Nabbar></Nabbar>
      </div>
      <div className='byq-tab'>
        {
          <Tabs activeKey={String(deptId)} onChange={(key) => setDeptId(Number(key))}>
            {
              title.map((item) => {
                return <Tabs.Tab title={item.departmentName} key={item.id}></Tabs.Tab>
              })
            }
          </Tabs>
        }
      </div>
      <div className="ks-sortbar">
        <div
          className={`ks-sort-item ${sortKey === '综合' ? 'ks-active' : ''}`}
          onClick={() => setSortKey('综合')}
        >综合</div>
        <div
          className={`ks-sort-item ${sortKey === '好评' ? 'ks-active' : ''}`}
          onClick={() => setSortKey('好评')}
        >好评</div>
        <div
          className={`ks-sort-item ${sortKey === '咨询量' ? 'ks-active' : ''}`}
          onClick={() => setSortKey('咨询量')}
        >咨询量</div>
        <div
          className={`ks-sort-item ks-price ${sortKey === '价格' ? 'ks-active' : ''}`}
          onClick={() => {
            if (sortKey !== '价格') { setSortKey('价格'); return }
            setPriceAsc(!priceAsc)
          }}
        >
          <span>价格</span>
          <span className="ks-arrows">
            <i className={`ks-arrow up ${priceAsc ? 'ks-up-on' : ''}`} />
            <i className={`ks-arrow down ${!priceAsc ? 'ks-down-on' : ''}`} />
          </span>
        </div>
      </div>
      <div className='byq-list'>
        {loading && (
          <div className='loading-container'>
            <div className='loading-spinner'></div>
            <div className='loading-text'>加载中...</div>
          </div>
        )}
        
        {error && !loading && (
          <div className='error-container'>
            <div className='error-text'>{error}</div>
            <div className='retry-btn' onClick={() => window.location.reload()}>重试</div>
          </div>
        )}
        
        {!loading && !error && current && (
          <div className='card' key={current.doctorId} >
            <div className='img-wrap'>
              <img className='doc-img' src={current.imagePic} alt='' />
            </div>
            <div className='meta'>
              <div className='name-row'>
                <div className='name'>{current.doctorName}</div>
                <div className='job'>{current.jobTitle}</div>
              </div>
              <div className='sub'>{current.inauguralHospital}</div>
              <div className='stats'>
                <span>好评率<b>{current.praiseNum}%</b></span>
                <span className='divider' />
                <span>服务患者数 <b>{current.serverNum}</b></span>
                <span className='more-dot' onClick={()=>navigate(`/ysxq/${current.doctorId}`)}/>
              </div>
              <div className='price-row'>
                <div className='price'>{current.servicePrice}H币</div>
                <div className='cta' onClick={()=>navigate('/zxun')}>立即咨询</div>
              </div>
            </div>
          </div>
        )}
        
        {!loading && !error && visible.length > 0 && (
          <div className='thumbs-row'>
            {/* 向左箭头 */}
            <div className='thumb-arrow-left' onClick={(e) => {
              e.stopPropagation();
              const len = visible.length
              if (len === 0) return
              if (activeIdx > 0) {
                setActiveIdx(activeIdx - 1)
              } else {
                // 上一页
                const prevPage = pageIdx > 0 ? pageIdx - 1 : pageCount - 1
                setPageIdx(prevPage)
                setActiveIdx(visible.length - 1)
              }
            }} />
            
            <div className='thumbs-scroll'>
              {visible.map((item, idx) => (
                <div className={`thumb ${activeIdx === idx ? 'on' : ''}`} key={item.doctorId} onClick={(e) => { e.stopPropagation(); setActiveIdx(idx) }}>
                  <img src={item.imagePic} alt='' />
                  <div className='thumb-name'>{item.doctorName}</div>
                </div>
              ))}
            </div>
            
            {/* 向右箭头 */}
            {visible.length > 0 && (
              <div className='thumb-arrow-right' onClick={(e) => {
                e.stopPropagation();
                const len = visible.length
                if (len === 0) return
                if (activeIdx < len - 1) {
                  setActiveIdx(activeIdx + 1)
                } else {
                  // 下一页
                  const nextPage = (pageIdx + 1) % pageCount
                  setPageIdx(nextPage)
                  setActiveIdx(0)
                }
              }} />
            )}
          </div>
        )}
        
        {!loading && !error && data.length > 0 && (
          <div className='thumb-indicator'><b>{start + activeIdx + 1}</b>/<span>{data.length}</span></div>
        )}
      </div>
    </div>
  )
}

export default Ks